package com.shxc.smarttrade.account.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.shxc.smarttrade.R;
import com.shxc.smarttrade.base.BaseActivity;
import com.shxc.smarttrade.currency.activity.WebActivity;
import com.shxc.smarttrade.dialog.DownloadDialog;
import com.shxc.smarttrade.dialog.UpdateDialog;
import com.shxc.smarttrade.info.Contents;
import com.shxc.smarttrade.utils.Loger;
import com.shxc.smarttrade.utils.ToastUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import org.xchris.view.annotation.ContentView;
import org.xchris.view.annotation.Event;
import org.xchris.view.annotation.ViewInject;

import java.io.File;

import okhttp3.Call;

/**
 * 关于我们
 */
@ContentView(R.layout.activity_aboutus)
public class AccountAboutUsActivity extends BaseActivity {

    private final int PERMISSIONS_REQUEST_READ_CONTACTS = 8;

    @ViewInject(R.id.title_textview)
    TextView title_textview;
    @ViewInject(R.id.left_imageview)
    ImageView left_imageview;
    @ViewInject(R.id.point_view)
    ImageView point_view;
    @ViewInject(R.id.versionname_textview)
    TextView versionname_textview;
    @ViewInject(R.id.newversion_textview)
    TextView newversion_textview;

    private UpdateDialog updateDialog;
    private DownloadDialog downloadDialog;

    private String apkUrl;
    private String apkName;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        String[] ss = spImp.getUpdateurl().split("/");
        apkName = ss[ss.length - 1];
        apkUrl = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + ss[ss.length - 1];

        title_textview.setText("关于我们");
        left_imageview.setVisibility(View.VISIBLE);
        versionname_textview.setText("SmartTrade v" + getVersionName());
        newversion_textview.setText(spImp.getNewversion());
        if (!spImp.getNewversion().equals(getVersionName())) {
            point_view.setVisibility(View.VISIBLE);
        } else {
            point_view.setVisibility(View.GONE);
        }

        updateDialog = new UpdateDialog(this, getResources().getIdentifier("MyDialog", "style", getPackageName()));
        downloadDialog = new DownloadDialog(this, getResources().getIdentifier("MyDialog", "style", getPackageName()));
    }

    @Event({R.id.left_imageview, R.id.about_trademaster_view, R.id.notice_view, R.id.privacy_view, R.id.update_view})
    private void onClickk(View view) {

        switch (view.getId()) {
            case R.id.left_imageview:
                //关闭
                finish();
                break;
            case R.id.about_trademaster_view:
                //关于外汇交易大师
                Intent i1 = new Intent(this, WebActivity.class);
                i1.putExtra("url", Contents.H5 + "/newpages/about.html");
                i1.putExtra("title", "关于SmartTrade");
                startActivity(i1);
                break;
            case R.id.notice_view:
                //须知
                Intent i2 = new Intent(this, WebActivity.class);
                i2.putExtra("url", Contents.H5 + "/newpages/notice.html");
                i2.putExtra("title", "交易条件和须知");
                startActivity(i2);
                break;
            case R.id.privacy_view:
                //隐私
                Intent i3 = new Intent(this, WebActivity.class);
                i3.putExtra("url", Contents.H5 + "/newpages/privacy-clause.html");
                i3.putExtra("title", "隐私条款");
                startActivity(i3);
                break;
            case R.id.update_view:
                //更新
                if (spImp.getNewversion().equals(getVersionName())) {
                    ToastUtils.showToast("当前版本是最新版，您不需要更新");
                } else {
                    updateDialog.showDialog(spImp.getUpdatemsg());
                    updateDialog.getCancel_textview().setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            updateDialog.dismiss();
                        }
                    });
                    updateDialog.getSubmit_textview().setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            updateDialog.dismiss();
                            if (fileIsExists(apkUrl)) {
                                installApk();
                            } else {
                                initPermissions();
                            }
                        }
                    });
                }
                break;
        }
    }

    /**
     * 获取版本号
     *
     * @return
     * @throws Exception
     */
    public String getVersionName() {
        try {
            // 获取packagemanager的实例
            PackageManager packageManager = getPackageManager();
            // getPackageName()是你当前类的包名，0代表是获取版本信息
            PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(), 0);
            String version = packInfo.versionName;
            return version;
        } catch (Exception e) {
            return getResources().getString(R.string.version_name);//TODO 修改版本号
        }
    }

    /**
     * 下载apk
     */
    private void okhttpDownload() {
        downloadDialog.show();
        OkHttpUtils.get()
                .url(spImp.getUpdateurl())
                .build()
                .execute(new FileCallBack(Environment.getExternalStorageDirectory().getAbsolutePath(),
                        apkName) {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Loger.e("download", "onError :" + e.getMessage());
                    }

                    @Override
                    public void inProgress(float progress, long total, int id) {
                        //super.inProgress(progress, total, id);
                        if (progress != 100) {
                            downloadDialog.getProgressbar().setProgress((int) (100 * progress));
                            downloadDialog.getPersent_textview().setText((int) (100 * progress) + "%");
                        } else {
                            downloadDialog.dismiss();
                        }
                    }

                    @Override
                    public void onResponse(File file, int id) {
                        Loger.e("download", "onResponse :" + file.getAbsolutePath());
                        installApk();
                    }
                });
    }

    //安装apk
    public void installApk() {
        String providerName = getApplicationInfo().packageName + ".provider";
        Loger.e("providerName", providerName);

        File file = new File(apkUrl);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        // 由于没有在Activity环境下启动Activity,设置下面的标签
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 24) { //判读版本是否在7.0以上
            //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
            Uri apkUri = FileProvider.getUriForFile(this, providerName, file);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//            intent.setDataAndType(apkUri, "applicationnd.android.package-archive");
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.parse("file://" + apkUrl),
//                    "applicationnd.android.package-archive");
                    "application/vnd.android.package-archive");

        }
        startActivity(intent);
    }

    // 授权管理 - 写入权限
    private void initPermissions() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                Toast.makeText(mContext, "请在 setting-应用管理 中开启此应用的储存授权。", Toast.LENGTH_SHORT).show();
            } else {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSIONS_REQUEST_READ_CONTACTS);
            }
        } else {
            okhttpDownload();
        }
    }

    // 授权返回
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {

        switch (requestCode) {
            case PERMISSIONS_REQUEST_READ_CONTACTS:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Loger.e("initPermissions", "同意授权");
                    okhttpDownload();
                } else {
                    Loger.e("initPermissions", "拒绝授权");
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    //判断文件是否存在
    public boolean fileIsExists(String strFile) {
        try {
            File f = new File(strFile);
            if (!f.exists()) {
                return false;
            }

        } catch (Exception e) {
            return false;
        }

        return true;
    }
}
